import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class TestAware implements BeanNameAware, ApplicationContextAware {
	private static ApplicationContext applicationContext = null;

	@Override
	public void setBeanName(String name) {

	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		if (TestAware.applicationContext != null) {
			System.out.println("TestAware中的ApplicationContext被覆盖, 原有ApplicationContext为:" + TestAware.applicationContext);
		}
		System.out.println("Spring容器启动，将容器实例注入到TestAware实例bean中");
		TestAware.applicationContext = applicationContext;
	}

	/**
	 * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
	 */
	public static <T> T getBean(String name) {
		return (T) applicationContext.getBean(name);
	}

	/**
	 * 从静态变量applicationContext中取得Bean, 自动转型为参数对象的类型.
	 */
	public static <T> T getBean(Class<T> requiredType) {
		return applicationContext.getBean(requiredType);
	}

}
